package com.hanserwei.han_picture.controller;

import cn.hutool.json.JSONUtil;
import com.hanserwei.han_picture.annotation.AuthCheck;
import com.hanserwei.han_picture.constant.UserConstant;
import com.hanserwei.han_picture.domain.common.ApiResponse;
import com.hanserwei.han_picture.manager.RedisManager;
import com.hanserwei.han_picture.service.PictureService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/redis")
@RequiredArgsConstructor
public class CleanRedisController {

    private final RedisManager redisManager;
    private final PictureService pictureService;

    @GetMapping("/refresh")
    @AuthCheck(requiredRole = UserConstant.ADMIN_ROLE)
    public ApiResponse<Boolean> refreshTagsCache() {
        // 1.先从数据库获取所有公共图片的标签
        List<String> allTags = pictureService.listAllTags();
        Map<String, Double> tagsMap = new HashMap<>();
        allTags.stream()
                .map(tags -> JSONUtil.toList(tags, String.class))
                .filter(Objects::nonNull)
                .flatMap(List::stream)
                .forEach(tag -> tagsMap.put(tag, tagsMap.getOrDefault(tag, 1.0) + 1.0));
        System.out.println(tagsMap);
        // 2.清除Redis的标签缓存
        redisManager.clearAllPictureTags();
        // 3.更新Redis的标签缓存
        redisManager.incrementTagsScore(tagsMap);
        return ApiResponse.success("成功", true);
    }
}
